# Maintainer: Andreas 'Segaja' Schleifer <segaja at archlinux dot org>

_gemname='kpeg'
pkgname="ruby-${_gemname}"
pkgver=1.3.2
pkgrel=4
pkgdesc='A simple PEG library for ruby'
arch=('any')
url="https://github.com/evanphx/${_gemname}"
license=('MIT')
depends=('ruby')
makedepends=('ruby-hoe' 'ruby-rake')
options=('!emptydirs')
source=("${url}/archive/v${pkgver}/${pkgname}-${pkgver}.tar.gz"
    # https://github.com/evanphx/kpeg/issues/56
    "${pkgname}_fix_tests.patch::${url}/commit/560e4abae250c1d53552ea38d112accb95268cfe.patch")
sha512sums=('8c05529af8c5ee1defb4401109ad8fd62cd39b6c278202e01781b294ee94395e8acdfe10d7e984b9ed5f1c11006dcbfa694c3315a0d9e5a085adb81bfbaa0848'
            '0ea92ded31efe8e06c33374f2a42ac8ca1876f201117220031d4d39a5d59925ea2f1b7154c7a41d81189cb522b2109400fd68585a91eddb03ad3bc0921d4036d')
b2sums=('91494f7e92bed6e285b4ed9be20738afba82ca75316e7e4537c4d15032dff906416c94f02ca1f5dec56d412c3910cbac072b63918b3ca1bbb71d1ca896d015da'
        '21069bc557a609b67eb72ca10c01f1b14c60e5b36f47ac2ab8a503d45ff4a94903e765b47cfd6eef04dccbfb4652246f12462ced348821281d0388fc80bf0c17')

prepare() {
  cd "${_gemname}-${pkgver}"

  patch --verbose --strip=1 --input="../${pkgname}_fix_tests.patch"

  # update gemspec/Gemfile to allow newer version of the dependencies
  sed --in-place --regexp-extended 's|~>|>=|g' "${_gemname}.gemspec"
}

build() {
  cd "${_gemname}-${pkgver}"

  local _gemdir="$(gem env gemdir)"

  gem build "${_gemname}.gemspec"

  gem install \
    --local \
    --verbose \
    --ignore-dependencies \
    --no-user-install \
    --install-dir "tmp_install/${_gemdir}" \
    --bindir "tmp_install/usr/bin" \
    "${_gemname}-${pkgver}.gem"

  # remove unrepreducible files
  rm --force --recursive --verbose \
    "tmp_install/${_gemdir}/cache/" \
    "tmp_install/${_gemdir}/gems/${_gemname}-${pkgver}/vendor/" \
    "tmp_install/${_gemdir}/doc/${_gemname}-${pkgver}/ri/ext/"

  find "tmp_install/${_gemdir}/gems/" \
    -type f \
    \( \
      -iname "*.o" -o \
      -iname "*.c" -o \
      -iname "*.so" -o \
      -iname "*.time" -o \
      -iname "gem.build_complete" -o \
      -iname "Makefile" \
    \) \
    -delete

  find "tmp_install/${_gemdir}/extensions/" \
    -type f \
    \( \
      -iname "mkmf.log" -o \
      -iname "gem_make.out" \
    \) \
    -delete
}

check() {
  cd "${_gemname}-${pkgver}"

  local _gemdir="$(gem env gemdir)"

  GEM_HOME="tmp_install/${_gemdir}" rake test
}

package() {
  cd "${_gemname}-${pkgver}"

  cp --archive --verbose tmp_install/* "${pkgdir}"

  install --verbose --directory --mode=0755 "${pkgdir}/usr/share/vim/vimfiles/"
  mv --verbose vim/syntax_kpeg/* "${pkgdir}/usr/share/vim/vimfiles/"

  install --verbose -D --mode=0644 LICENSE --target-directory "${pkgdir}/usr/share/licenses/${pkgname}"
  install --verbose -D --mode=0644 *.rdoc --target-directory "${pkgdir}/usr/share/doc/${pkgname}"
}
